<template>
  <div class="userPwd-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>重置密码</span>
      </div>
      <div>
        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="pwdForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="原密码" prop="old_pwd">
            <el-input v-model="ruleForm.old_pwd"></el-input>
          </el-form-item>
          <el-form-item label="新密码" prop="new_pwd">
            <el-input v-model="ruleForm.new_pwd"></el-input>
          </el-form-item>
          <el-form-item label="确认新密码" prop="re_pwd">
            <el-input v-model="ruleForm.re_pwd"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm('pwdForm')">修改密码</el-button>
            <el-button @click="resetForm('pwdForm')">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script>
import { updatePwdAPI } from '@/api'
export default {
  data() {
    const samePwdFn = (rule, value, callback) => {
      // 注意:必须在data函数里定义此箭头函数，才能确保this.form使用
      if (this.ruleForm.new_pwd !== value) {
        // 如果验证失败，则调用回调函数时，指定一个 Error 对象。
        callback(new Error('两次输入的密码不一致!'))
      } else {
        // 如果验证成功，则直接调用 callback 回调函数即可。
        callback()
      }
    }
    return {
      ruleForm: {
        old_pwd: '',
        new_pwd: '',
        re_pwd: ''
      },
      rules: {
        old_pwd: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            pattern: /^\S{6,15}$/,
            message: '密码长度必须是6-15位的非空字符串',
            trigger: ['blur', 'change']
          }
        ],
        new_pwd: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          {
            pattern: /^\S{6,15}$/,
            message: '密码长度必须是6-15位的非空字符串',
            trigger: ['blur', 'change']
          }
        ],
        re_pwd: [
          { required: true, message: '请再次确认新密码', trigger: 'blur' },
          { validator: samePwdFn, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 提交修改按钮
    submitForm(formName) {
      // eslint-disable-next-line
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          const { data } = await updatePwdAPI(this.ruleForm)
          console.log(data)
          if (data.code === 0) {
            this.$message({
              message: '更新密码成功!',
              type: 'success'
            })
            this.ruleForm.old_pwd = ''
            this.ruleForm.new_pwd = ''
            this.ruleForm.re_pwd = ''
          } else {
            this.$message.error('更新密码失败!')
          }
        } else {
          return false
        }
      })
    },
    // 重置按钮
    resetForm(formName) {
      this.$refs[formName].resetFields()
    }
  }
}
</script>

<style lang="less" scoped>
.el-input {
  width: 400px;
}
</style>
